package com.aaa.vegetablemarketexpress.service.impl;

import com.aaa.vegetablemarketexpress.dao.RoleDao;
import com.aaa.vegetablemarketexpress.entity.Role;
import com.aaa.vegetablemarketexpress.entity.User;
import com.aaa.vegetablemarketexpress.service.RoleService;
import com.aaa.vegetablemarketexpress.util.CustomException;
import com.aaa.vegetablemarketexpress.util.Page;
import com.aaa.vegetablemarketexpress.util.ResultStatus;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @FileName: RoleServiceImpl
 * @Description:
 * @Author: 张钰哲
 * @CreateTime: 2025/9/9 10:13
 * @Version: 1.0.0
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    private RoleDao roleDao;
    @Resource
    private HttpSession session;
    /**
     * 分页查询
     * @param page
     * @return
     */
    @Override
    public PageInfo<Role> queryByPage(Page<Role> page) {
        Integer pageSize = page.getPageSize();
        Integer pageNo = page.getPageNo();
        if (pageNo == null || pageSize == null||pageNo == 0||pageSize == 0) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), ResultStatus.PARAM_ISNULL.getStatusMsg());
        }
        PageHelper.startPage(pageNo, pageSize);
        Role data = page.getData();
        List<Role> roleList = roleDao.queryByParam(data);
        return new PageInfo<>(roleList);
    }

    /**
     *
     * @param roleId
     * @return
     */
    @Override
    public Role queryByRoleId(Long roleId) {
        return roleDao.queryByRoleId(roleId);
    }

    /**
     *
     * @param role
     * @return
     */
    @Override
    public int add(Role role) {
        // 校验参数
        validateRole(role);
        // 检查角色名称是否唯一
        Role existRole = roleDao.checkRoleNameUnique(role.getRoleName());
        if (existRole != null) {
            throw new CustomException(ResultStatus.DATA_ROLENAME_EXIST.getStatusCode(), ResultStatus.DATA_ROLENAME_EXIST.getStatusMsg());
        }

        // 检查角色权限字符串是否唯一
        existRole = roleDao.checkRoleKeyUnique(role.getRoleKey());
        if (existRole != null) {
            throw new CustomException(ResultStatus.DATA_ROLEKEY_EXIST.getStatusCode(), ResultStatus.DATA_ROLEKEY_EXIST.getStatusMsg());
        }
        role.setCreateTime(new Date());
        role.setStatus("0");
        role.setDelFlag("0");
        User userList = (User)session.getAttribute("userInfo");
        String userName = userList.getUserName();
        role.setCreateBy(userName);
        return roleDao.add(role);
    }

    /**
     *
     * @param role
     * @return
     */
    @Override
    public int update(Role role) {
        // 校验参数
        validateRole(role);

        if (role.getRoleId() == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "角色ID不能为空");
        }

        // 检查角色名称是否唯一（排除当前角色）
        Role existRole = roleDao.checkRoleNameUnique(role.getRoleName());
        if (existRole != null && !existRole.getRoleId().equals(role.getRoleId())) {
            throw new CustomException(ResultStatus.DATA_ROLENAME_EXIST.getStatusCode(), ResultStatus.DATA_ROLENAME_EXIST.getStatusMsg());
        }

        // 检查角色权限字符串是否唯一（排除当前角色）
        existRole = roleDao.checkRoleKeyUnique(role.getRoleKey());
        if (existRole != null && !existRole.getRoleId().equals(role.getRoleId())) {
            throw new CustomException(ResultStatus.DATA_ROLEKEY_EXIST.getStatusCode(), ResultStatus.DATA_ROLEKEY_EXIST.getStatusMsg());
        }
        role.setUpdateTime(new Date());
        User userList = (User)session.getAttribute("userInfo");
        String userName = userList.getUserName();
        role.setUpdateBy(userName);
        return roleDao.update(role);
    }

    /**
     *
     * @param roleId
     * @return
     */
    @Override
    public int delete(Long roleId) {
        if (roleId == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "角色ID不能为空");
        }

        // 检查角色是否存在
        Role role = roleDao.queryByRoleId(roleId);
        if (role == null) {
            throw new CustomException(ResultStatus.DATA_NOT_EXIST.getStatusCode(), ResultStatus.DATA_NOT_EXIST.getStatusMsg());
        }
        return roleDao.delete(roleId);
    }

    /**
     *检查角色名称是否唯一
     * @param roleName
     * @return
     */
    @Override
    public Role checkRoleNameUnique(String roleName) {
        if (roleName == null || roleName.trim().isEmpty()) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "角色名称不能为空");
        }
        return roleDao.checkRoleNameUnique(roleName);
    }
    /**
     * 校验角色参数
     * @param role
     */
    private void validateRole(Role role) {
        if (role == null) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "角色信息不能为空");
        }

        if (role.getRoleName() == null || role.getRoleName().trim().isEmpty()) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "角色名称不能为空");
        }

        if (role.getRoleKey() == null || role.getRoleKey().trim().isEmpty()) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "角色权限字符串不能为空");
        }

        if (role.getRoleName().length() > 30) {
            throw new CustomException(ResultStatus.PARAM_INVALID.getStatusCode(), "角色名称长度不能超过30个字符");
        }

        if (role.getRoleKey().length() > 100) {
            throw new CustomException(ResultStatus.PARAM_INVALID.getStatusCode(), "角色权限字符串长度不能超过100个字符");
        }

        if (role.getRemark() != null && role.getRemark().length() > 500) {
            throw new CustomException(ResultStatus.PARAM_INVALID.getStatusCode(), "备注长度不能超过500个字符");
        }
    }

    /**
     * 根据角色名称查询
     * @param roleName 角色名称（如"商家"）
     * @return
     */
    @Override
    public Role queryByRoleName(String roleName) {
        if (roleName == null || roleName.trim().isEmpty()) {
            throw new CustomException(ResultStatus.PARAM_ISNULL.getStatusCode(), "角色名称不能为空");
        }
        return roleDao.checkRoleNameUnique(roleName); // 复用已有的查询方法
    }
    /**
     * 根据用户id查询当前用户角色集合(shiro)
     *
     * @param userId 主键
     * @return 角色集合
     */
    @Override
    public List<Role> queryByUserId(Long userId) {
        return roleDao.queryByUserId(userId);
    }
}
